<template>
  <div class="">
    <el-card class="max-w-6xl mx-auto rounded-xl shadow-lg">
      <template #header>
        <div class="flex items-center justify-between">
          <h2 class="text-2xl font-semibold text-gray-800">我收藏的菜品</h2>
        </div>
      </template>

      <!-- 菜品列表 -->
      <div v-loading="loading">
        <el-row v-if="dishList.length > 0" :gutter="20">
          <el-col v-for="dish in dishList" :key="dish.id" :span="8" class="mb-5">
            <DishCard :dish="dish"/>
          </el-col>
        </el-row>
        <el-empty v-else description="暂无收藏的菜品"></el-empty>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          v-if="total > 0"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[9, 18, 27]"
          :total="total"
          background
          class="mt-6 flex justify-center"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import request from '@/utils/request'; // 统一接口请求工具
import DishCard from '@/components/DishCard.vue'; // 导入 DishCard 组件

// 响应式数据
const loading = ref(false); // 加载状态
const dishList = ref([]); // 菜品列表数据
const total = ref(0); // 总条数
const currentPage = ref(1); // 当前页码
const pageSize = ref(9); // 每页大小，默认为3列，每行3个，所以是9

// 搜索表单数据
const searchForm = reactive({
  page: currentPage.value,
  size: pageSize.value,
  param: {
    businessType: 1, // 业务类型：菜品
  },
  orders: [] // 排序字段，目前无需排序，可根据需求添加
});

/**
 * 获取收藏菜品列表
 */
const handleGetCollectedMerchants = async () => {
  loading.value = true;
  // 更新分页参数到请求体
  searchForm.page = currentPage.value;
  searchForm.size = pageSize.value;

  // 接口请求，无需try catch和判断code
  const res = await request.post('/collect/page', searchForm);

  // 直接赋值，按照要求无需判断code
  dishList.value = res.records || [];
  total.value = res.total;
  loading.value = false;
};

/**
 * 处理每页大小改变
 * @param {number} newSize - 新的每页大小
 */
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  handleGetCollectedMerchants();
};

/**
 * 处理当前页码改变
 * @param {number} newPage - 新的页码
 */
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  handleGetCollectedMerchants();
};

// 组件挂载时获取数据
onMounted(() => {
  handleGetCollectedMerchants();
});
</script>

<style scoped>
.font-inter {
  font-family: 'Inter', sans-serif;
}

.el-card {
  --el-card-border-radius: 12px;
  --el-card-padding: 20px;
}

/* 确保分页组件的flex布局能正确居中 */
.el-pagination.is-background .btn-next,
.el-pagination.is-background .btn-prev,
.el-pagination.is-background .el-pager li {
  border-radius: 6px;
}
</style>
